//
//  ZSMAFNetWork.m
//  FoodAndDrinkAndHealthy
//
//  Created by dlios on 15-9-1.
//  Copyright (c) 2015年 zhoushengmin. All rights reserved.
//

#import "ZSMAFNetWork.h"

@implementation ZSMAFNetWork

+ (void)geturl:(NSString *)url
         body:(id)body
       result:(ZSMResult)result
   headerFile:(NSDictionary *)headerFile
      success:(void(^)(id result))success
      failure:(void(^)(NSError *error))failure{

#pragma warning 识别不了/和:这两字符
    NSString *strUrl = [url stringByReplacingOccurrencesOfString:@"/" withString:@""];
    strUrl = [[[[[[[[[strUrl stringByReplacingOccurrencesOfString:@":" withString:@""]stringByReplacingOccurrencesOfString:@"_" withString:@""]stringByReplacingOccurrencesOfString:@"&" withString:@""]stringByReplacingOccurrencesOfString:@"?" withString:@""]stringByReplacingOccurrencesOfString:@"=" withString:@""]stringByReplacingOccurrencesOfString:@"." withString:@""]stringByReplacingOccurrencesOfString:@"%" withString:@""]stringByReplacingOccurrencesOfString:@"-" withString:@""]substringFromIndex:50];
////    // 哈希转换,可惜会重复
////    NSString *strUrl = [NSString stringWithFormat:@"/%@.plist",url];
//    //先找到沙盒路径
    NSArray *sandox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesPath = sandox[0];
    //利用文件管理者在caches文件夹建一个新的文件夹
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"缓存"];
//
//    // 通过manager进行文件夹的创建
    [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
//    //新路径
    NSString *str = [NSString stringWithFormat:@"%@.plist",strUrl];
    NSString *strPath =  [filePath stringByAppendingPathComponent:str];
    NSLog(@"%@",strPath);
////    先反归档
//    
    
    if ([NSKeyedUnarchiver unarchiveObjectWithFile:strPath] != nil) {
        
        success([NSKeyedUnarchiver unarchiveObjectWithFile:strPath]);
        
        
    }else {
    
        // 1.获取网络请求管理类
        AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
        // 2.为网络请求加请求头
        if (headerFile) {
            for (NSString *key in headerFile.allKeys) {
                [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
            }
        }
        // 3.设置返回值类型
        switch (result) {
            case ZSMData:
                manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                break;
            case ZSMJSON:
                //            manager.responseSerializer = [AFJSONResponseSerializer serializer];
                break;
            case ZSMXML:
                manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
                break;
            default:
                break;
        }
        // 4.设置网络请求返回值所支持的参数类型
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",nil]];
        
        // 5.发送网络请求
        [manager GET:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (responseObject) {
                //归档
                [NSKeyedArchiver archiveRootObject:responseObject toFile:strPath];
                
                success(responseObject);
               
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (error) {
                //失败回调
                failure(error);
            }
            
        }];

        
    }

    
    
    
}

+ (void)posturl:(NSString *)url
          body:(id)body
        result:(ZSMResult)result
  requestStyle:(ZSMRequestStyle)requestStyle
    headerFile:(NSDictionary *)headerFile
       success:(void(^)(id result))success
       failure:(void(^)(NSError *error))failure{

    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *sandBoxPath = sandBox[0];
    // 创建一个文件管理者
    NSFileManager *manager1=[NSFileManager defaultManager];
    // 给要创建的文件夹拼接一个路径
    NSString *filePath=[sandBoxPath stringByAppendingPathComponent:@"缓存"];
    // 通过manager进行文件夹的创建
    [manager1 createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    // 创建一个沙盒路径,缓存什么就用对应的名字作为文件名字
    NSString *cacheBody = [NSString stringWithFormat:@"%@.plist",body];
    NSString *cachesPath = [filePath stringByAppendingPathComponent:cacheBody];
    // 反归档
    if ([NSKeyedUnarchiver unarchiveObjectWithFile:cachesPath] != nil) {
        success([NSKeyedUnarchiver unarchiveObjectWithFile:cachesPath]);
    }

    
        // 1.获取网络请求管理类
        AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
        // 2.网络请求请求体body的类型
        switch (requestStyle) {
            case ZSMRequestJSON:
                manager.requestSerializer = [AFJSONRequestSerializer serializer];
                break;
            case ZSMRequestString:
                [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
                    return parameters;
                    
                }];
                break;
                
            default:
                break;
        }
        
        // 3.为网络请求加请求头
        if (headerFile) {
            for (NSString *key in headerFile.allKeys) {
                [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
            }
        }
        // 4.网络请求返回值的数据类型
        switch (result) {
            case ZSMData:
                manager.responseSerializer=[AFHTTPResponseSerializer serializer];
                break;
            case ZSMJSON:
                break;
            case ZSMXML:
                manager.responseSerializer=[AFXMLParserResponseSerializer serializer];
                break;
            default:
                break;
        }
        // 5.设置返回值支持的参数类型
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
        // 6.发送网络请求
        [manager POST:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (responseObject) {
                // 成功回调
                [NSKeyedArchiver archiveRootObject:responseObject toFile:cachesPath];

                // 成功回调
                success(responseObject);
                NSLog(@"%@",cachesPath);
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (error) {
                // 失败回调
                failure(error);
            }
            
        }];
   
    
}


+(void)SeekPosturl:(NSString *)url
              body:(id)body
            result:(ZSMResult)result
      requestStyle:(ZSMRequestStyle)requestStyle
        headerFile:(NSDictionary *)headerFile
           success:(void(^)(id result))success
           failure:(void(^)(NSError *error))failure{
    // 1.获取网络请求管理类
    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
    // 2.网络请求请求体body的类型
    switch (requestStyle) {
        case ZSMRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case ZSMRequestString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
                return parameters;
                
            }];
            break;
            
        default:
            break;
    }
    
    // 3.为网络请求加请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    // 4.网络请求返回值的数据类型
    switch (result) {
        case ZSMData:
            manager.responseSerializer=[AFHTTPResponseSerializer serializer];
            break;
        case ZSMJSON:
            break;
        case ZSMXML:
            manager.responseSerializer=[AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    // 5.设置返回值支持的参数类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    // 6.发送网络请求
    [manager POST:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            // 成功回调
            success(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error) {
            // 失败回调
            failure(error);
        }
        
    }];

}




@end
